package org.new9uy.tetris.controller;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import org.new9uy.tetris.Settings;
import org.new9uy.tetris.game.type.Game;
import org.new9uy.tetris.model.Gravity;
import org.new9uy.tetris.model.Matrix;

public class KeyController implements KeyListener{
	
	private Matrix mtx;
	private Gravity grav;
	private boolean speeding;
	private boolean rotateDone;
	
	public KeyController(Matrix mtx, Gravity grav){
		this.mtx=mtx;
		this.grav=grav;
		speeding=false;
		rotateDone=false;
	}
	
	private boolean dontlisten() {
		return grav.getPause() || grav.getIgnoreKeys();
	}

	public void keyPressed(KeyEvent e)
	{
		//TODO: remove this para [for testing]
		if (e.getKeyCode()==KeyEvent.VK_P)
			Game.current().pauseAllGravities(!grav.getPause());
		
		if(dontlisten()) {return;}
		
		int k = e.getKeyCode();
		if (k==Settings.CONTROLLER_LEFT){ 
			if(!grav.getPause()) mtx.moveTetrimino('x',-1);
		}
		else if (k==Settings.CONTROLLER_RIGHT){
			if(!grav.getPause()) mtx.moveTetrimino('x',1);
		}
		else if (k==Settings.CONTROLLER_ROTATE) {
			if(!grav.getPause()){
				if(!rotateDone) 
					mtx.rotateTetrimino();
					rotateDone=true;
			}
		}
		else if (k==Settings.CONTROLLER_DROP) 
		{
				grav.drop();
		}
		else if (k==Settings.CONTROLLER_SPEEDUP) {
			if(!speeding) {
				speeding=true; grav.speedUp();
			}
		}
	}
	
	public void keyTyped(KeyEvent e){
	}
	
	public void keyReleased(KeyEvent e)
	{
		if(dontlisten()) return;
		
		int k = e.getKeyCode();
		if (k==Settings.CONTROLLER_SPEEDUP)
			{grav.slowDown(); speeding=false;}
		else if (k==Settings.CONTROLLER_ROTATE) rotateDone=false;
	}
}
